<?php
/*
 * Created on 11-05-2012
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
 
App::uses('AppModel', 'Model');
class Court extends AppModel {
	public $name = 'Court';
	
	public $belongsTo = 'FieldType';
	
	public $hasMany = array(
        'Reservation' => array(
			'className'  => 'Reservation',
			'order'      => 'Reservation.start_time DESC'
		)
	);

	public function getAvailableStartTimes($id = 0, $dateText = 'YYYY-MM-DD') {
		$startTimes = array();
		for($i=0; $i<24; $i++) {
			$keyval = date("H:i:s", mktime($i, 0, 0));
			$startTimes[$keyval] = $keyval;
		}
		$this->id = $id;
		$court = $this->read();
		if($court != null) {
			// Usuwamy czasy sprzed godziny otwarcia kortu
			foreach($startTimes as $key => $value) {
				if($key < substr($court['Court']['start_time'], 0, 5)) {
					
					unset($startTimes[$key]);
				}
			}
			// Usuwamy czasy po godzinie zakmnięcia kortu
			foreach($startTimes as $key => $value) {
				if($key >= substr($court['Court']['end_time'], 0, 5)) {
					unset($startTimes[$key]);
				}
			}
			// Usuwamy czasy zajęte przez rezerwacje
			foreach($court['Reservation'] as $reservation) {
				$startTime = preg_split("/[\s]+/", $reservation['start_time']);
				if($startTime[0] == $dateText) {
					unset($startTimes[$startTime[1]]);
				}
			}
			return $startTimes;
		} 
		return $startTimes;
	}
	public $validate = array(
		'name'=>array(
			'Brak nazwy'=>array(
				'rule'=>'notEmpty',
				'message'=>'Brak nazwy.'
			)
		),
		'start_time'=>array(
			'Po end_time'=>array(
				'rule'=>'checkTime',
				'message'=>'Czas otwarcia musi być wcześniejszy niż czas zamknięcia'
				)
		)
	);
	
	public function checkTime($data) {
		if ($data['start_time'] < $this->data['Court']['end_time']) {
			return true;
		}
		return false;
	}
}
?>
